<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

require_once 'const/RequestConst.php';
require_once "const/DBConst.php";

/**
 * Description of AccountManager
 *
 * @author lidejia
 */
class Business_AccountManager {

    public static function register($registerInfo) {
        try {
            $email = $registerInfo->getEmail();
            $password = $registerInfo->getPassword();
            $password = md5($password);
            $account = new Application_Model_Account($email, $password, "U");
            $id = Application_Model_AccountMapper::insert($account);
//
            $name = $registerInfo->getName();
            $address = $registerInfo->getAddress();
            $phone = $registerInfo->getPhone();
            $profile = new Application_Model_Profile($name, $address, $phone, $id);
            Application_Model_ProfileMapper::insert($profile);
            Business_AccountManager::verify($email, $password);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public static function verify($email, $password, $isAdmin = false) {
        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Registry::get("database"), T_ACCOUNT, C_EMAIL, C_PASSWORD, "MD5(?)");
        $authAdapter->setIdentity($email);
        $authAdapter->setCredential($password);
        $result = Zend_Auth::getInstance()->authenticate($authAdapter);
        if ($result->isValid()) {
            if ($isAdmin) {
                if ($result->getIdentity() == "admin") {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    public static function requireLogin($response, $loginURL, $returnURL) {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $directPath = $loginURL . "?" . P_RETURNURL . "=" . urlencode($returnURL);
            $response->setRedirect($directPath);
        }
    }

    public static function logout($response, $returnURL) {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $response->setRedirect($returnURL);
    }

    public static function getUserIdentity() {
        $auth = Zend_Auth::getInstance();
        return $auth->getIdentity();
    }

}

?>
